package br.com.portalecbahia.connectionservices;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import blueprint.software.blueframe.synchronize.HTTPConnect;
import br.com.portalecbahia.dao.ActionDAO;
import br.com.portalecbahia.dao.MatchDAO;
import br.com.portalecbahia.listner.ActionListeners;
import br.com.portalecbahia.model.Match;
import br.com.portalecbahia.util.PortalECBahiaUtil;

public class SynchronizeActions extends AsyncTask<Match, Void, Boolean> {

	private ActionListeners listeners;
	private HTTPConnect connect;
	private ActionDAO dao;
	private Context context;
	
	public SynchronizeActions (Context context){
	
		this.context = context;
		
		this.listeners = (ActionListeners)context;
	}
	
	@Override
	protected void onPreExecute() {
	
	}
	
  
    @Override
    protected void onPostExecute(Boolean result) {               
       
       	listeners.onSynchronizeActionComplete(result);
   }

	@Override
	protected Boolean doInBackground(Match... params) {
		
		try{
			Match match = params[0];
			connect = new HTTPConnect(PortalECBahiaUtil.urlServer+"/FindAllActionMatch?idMatch="+match.getId());
			JSONArray jsonArray =  connect.getArray("", null);
			
			if(jsonArray!=null && jsonArray.length()>0){
				dao = new ActionDAO(context);
				dao.removeByMatch(match);
				dao.insertByMatch(jsonArray, match);
				dao.updateLastUpdateAction(match);
			}
			connect = new HTTPConnect(PortalECBahiaUtil.urlServer+"/FindMatchScore?idMatch="+match.getId());
			JSONObject jsonObject =  connect.getObject("", null);
			
			if(jsonObject!=null && jsonObject.length()>0){
				int home = (Integer) jsonObject.get("homeGoal");
				int away =  (Integer) jsonObject.get("awayGoal");
				new MatchDAO(context).updateScore(home,away, match) ;
			}
			
		}catch (Exception e) {
			Log.e(PortalECBahiaUtil.TAG, e.toString());
			return false;
		}
		
		return true;
	}
}

